$.fn.dndhover = function(options) {

    return this.each(function() {

        var self = $(this);
        var collection = $();

        self.on('dragenter', function(event) {
            if (collection.size() === 0) {
                self.trigger('dndHoverStart',[event.originalEvent]);
            }
            collection = collection.add(event.target);
            event = event.originalEvent;
            event.stopPropagation();
            event.preventDefault();
        });
        self.on('dragover', function(event) {
            event = event.originalEvent;
            event.stopPropagation();
            event.preventDefault();
        });
        self.on('dragleave', function(event) {
            /*
             * Firefox 3.6 fires the dragleave event on the previous element
             * before firing dragenter on the next one so we introduce a delay
             */
            event = event.originalEvent;
            event.stopPropagation();
            event.preventDefault();
            setTimeout(function() {
                collection = collection.not(event.target);
                if (collection.size() === 0) {
                    self.trigger('dndHoverEnd');
                }
            }, 1);
        });
    });
};


$(document).ready(function()
{
    if (Modernizr.draganddrop)
    {
        $(".HTML5DnD_ProgressText").html("<p>Drag and drop files here to upload them. You can also use the form below and hit 'Upload'</p>");
        $(".HTML5DnD_Dropbox").bind("drop", onDropFile);
        $('.HTML5DnD_Dropbox').dndhover().on({
            'dndHoverStart': function(event) {$(this).addClass('HTML5DnD_DragOver'); event.stopPropagation();},
            'dndHoverEnd': function(event) {$(this).removeClass('HTML5DnD_DragOver'); event.stopPropagation();}
        });
    }
});

function onDropFile(evt)
{
    evt = evt.originalEvent;
    $(this).removeClass("HTML5DnD_DragOver");
    evt.stopPropagation();
    evt.preventDefault();
    var files = evt.target.files || evt.dataTransfer.files;
    var inputs = new FormData($(this).find('form')[0]);
    var uploader = $(this);
    for (var index=0;index<files.length;index++)
    {
        inputs.append('file[]',files[index]);
    }
    $.ajax({
        url: getUploadURL(),
        data: inputs,
        cache: false,
        contentType: false,
        context: $(this),
        processData: false,
        type: 'POST',
        xhr: function()
        {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function(progress)
                {
                    var total = progress.total || progress.totalSize;
                    var position = progress.position || progress.loaded;
                    var percentage = Math.floor((position / total) * 100);
                    uploader.find(".HTML5DnD_ProgressBorder").css('display','block');
                    uploader.find(".HTML5DnD_Progress").css('width',percentage + '%');
                    if (percentage == 100)
                    {
                        uploader.find(".HTML5DnD_ProgressText").html("Uploading complete. Processing files...");
                    }
                    else {uploader.find(".HTML5DnD_ProgressText").html("Uploading: " + percentage.toFixed(1) + "%");}
                }, false);
            }//if
            return xhr;
        }
    })
    .done(function(){window.location.hash=$(this).attr("id"); window.location.reload(true);})
    .fail(function(){$(this).find(".HTML5DnD_ProgressText").html("Upload failed");})
    //.always(function(){$(this).find(".HTML5DnD_ProgressText").html("Something happened");})
    ;
};

